#!/bin/bash

# 书海拾贝停止脚本

PID_FILE="/home/bookocean/app.pid"

# 颜色输出
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${YELLOW}🛑 停止书海拾贝应用...${NC}"

if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if ps -p $PID > /dev/null 2>&1; then
        echo "正在停止应用 (PID: $PID)..."
        kill $PID
        
        # 等待进程结束
        for i in {1..10}; do
            if ! ps -p $PID > /dev/null 2>&1; then
                break
            fi
            echo "等待应用停止... ($i/10)"
            sleep 1
        done
        
        # 如果还没停止，强制杀死
        if ps -p $PID > /dev/null 2>&1; then
            echo "强制停止应用..."
            kill -9 $PID
        fi
        
        rm -f "$PID_FILE"
        echo -e "${GREEN}✅ 应用已停止${NC}"
    else
        echo -e "${YELLOW}应用未在运行 (PID文件存在但进程不存在)${NC}"
        rm -f "$PID_FILE"
    fi
else
    echo -e "${YELLOW}PID文件不存在，尝试查找进程...${NC}"
    
    # 查找并停止相关进程
    PIDS=$(ps aux | grep "book-ocean-1.0.0.jar" | grep -v grep | awk '{print $2}')
    
    if [ -n "$PIDS" ]; then
        echo "找到相关进程: $PIDS"
        echo $PIDS | xargs kill
        sleep 2
        
        # 检查是否还有进程运行
        REMAINING=$(ps aux | grep "book-ocean-1.0.0.jar" | grep -v grep | awk '{print $2}')
        if [ -n "$REMAINING" ]; then
            echo "强制停止剩余进程: $REMAINING"
            echo $REMAINING | xargs kill -9
        fi
        
        echo -e "${GREEN}✅ 应用已停止${NC}"
    else
        echo -e "${YELLOW}未找到运行中的应用${NC}"
    fi
fi
